package com.itguigu.security.filter;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.itguigu.common.jwt.JwtUtils;
import com.itguigu.common.result.Result;
import com.itguigu.common.result.ResultCodeEnum;
import com.itguigu.common.utils.ResponseUtil;
import com.itguigu.security.custom.LoginUserInfoHelper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 认证解析token过滤器
 */
@Slf4j
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private RedisTemplate redisTemplate;

    public TokenAuthenticationFilter(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("uri:" + request.getRequestURI());
        String requestURI = request.getRequestURI();
        if ("/admin/system/index/login".equals(requestURI)) {
            // 登录请求 直接放行
            filterChain.doFilter(request, response);
            return;
        }

        // 判断认证
        // 根据请求 获取认证信息
        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
        if (authentication == null) {
            ResponseUtil.out(response, Result.build(null, ResultCodeEnum.PERMISSION));
        } else {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            filterChain.doFilter(request, response);
        }

    }

    /**
     * 获取认证
     * 修改认证 , 当查到用户名不为空时 , 将用户信息保存到 登录用户信息帮助工具类当中
     * @param request
     * @return
     */
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // token置于header里
        String token = request.getHeader("token");
        logger.info("token:" + token);
        if (!StringUtils.isEmpty(token)) {
            Claims claims = JwtUtils.ParserJwt(token);
            String username = (String) claims.get("username");
            log.info("username:" + username);
            if (!StringUtils.isEmpty(username)) {
                // 保存数据到 LoginUserInfoHelper
                /**
                 *         Object id = claims.get("userId");
                 *         Integer integer = (Integer) id;
                 *         log.info(String.valueOf(integer));
                 * //        Long userId = new Long(integer.intValue());
                 *         Long userId = (long) integer;
                 */
                Object id = claims.get("userId");
                Integer integer = (Integer) id;
                log.info(String.valueOf(integer));
                Long userId = (long) integer;
                LoginUserInfoHelper.setUserId(userId);
                LoginUserInfoHelper.setUsername(username);

                String authoritiesString = (String) redisTemplate.opsForValue().get(username);
                List<Map> mapList = JSON.parseArray(authoritiesString, Map.class);
                List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                for (Map map : mapList) {
                    authorities.add(new SimpleGrantedAuthority((String) map.get("authority")));
                }
                return new UsernamePasswordAuthenticationToken(username, null, authorities);
            } else {
                return new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
            }
        }
        return null;
    }
}
